package org.log4jconfig.xml.editor.utils;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
import org.eclipse.wst.sse.core.utils.StringUtils;
import org.eclipse.wst.xml.core.internal.document.DocumentImpl;
import org.eclipse.wst.xml.core.internal.parser.regions.AttributeNameRegion;
import org.eclipse.wst.xml.ui.internal.contentassist.ContentAssistRequest;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@SuppressWarnings("restriction")
public class ContentAssistRequestUtils {

	/**
	 * Returns the attribute name for which ContentAssist is going to be
	 * proposed to the user
	 * 
	 * @param contentAssistRequest
	 * @return
	 */
	public static String extractAttributeName(ContentAssistRequest contentAssistRequest) {
		ITextRegion region = contentAssistRequest.getRegion();
		ITextRegionList regions = contentAssistRequest.getDocumentRegion().getRegions();
		while (!(region instanceof AttributeNameRegion)) {
			region = regions.get(regions.indexOf(region) - 1);
		}

		return contentAssistRequest.getDocumentRegion().getFullText(region).trim();

	}

	public static String extractAttributeMatchValue(ContentAssistRequest contentAssistRequest) {
		String match = contentAssistRequest.getMatchString();
		return StringUtils.stripQuotes(match).trim();
	}

	public static String extractAttributeCurrentValue(ContentAssistRequest contentAssistRequest) {
		String value = contentAssistRequest.getText();
		// remove heading and trailing double quotes if present...
		return StringUtils.stripQuotes(value).trim();
	}
	
	public static String extractTagName(ContentAssistRequest contentAssistRequest) {
		return contentAssistRequest.getNode().getNodeName();
	}

	public static List<String> findAllAppenderNames(ContentAssistRequest contentAssistRequest) {
		List<String> names = new ArrayList<String>();
		// move up to root node of this xml document
		Node node = contentAssistRequest.getNode().getParentNode();
		while (!(node.getParentNode() instanceof DocumentImpl)) {
			node = node.getParentNode();
		}
		// scan children nodes from here (current node is <log4j:configuration>)
		NodeList nodeList = node.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node item = nodeList.item(i);
			if ("appender".equalsIgnoreCase(item.getNodeName())) {
				names.add(item.getAttributes().getNamedItem("name").getNodeValue());
			}
		}
		return names;
	}
}
